﻿using System;
using System.Collections.Generic;

using System.Text;

namespace RoughJs.Ast
{
    /// <summary>

    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
 
    /// 
    /// 实现arguments
    /// ECMA 10.1.8
    /// </summary>
    public class Arguments : IdScriptableObject
    {

        // Fields to hold caller, callee and length properties,
        // where NOT_FOUND value tags deleted properties.
        // In addition if callerObj == NULL_VALUE, it tags null for scripts, as
        // initial callerObj == null means access to caller arguments available
        // only in JS <= 1.3 scripts
        private Object callerObj;
        private Object calleeObj;
        private Object lengthObj;

        private NativeCall activation;

        // Initially args holds activation.getOriginalArgs(), but any modification
        // of its elements triggers creation of a copy. If its element holds NOT_FOUND,
        // it indicates deleted index, in which case super class is queried.
        private Object[] args;

        public Arguments(NativeCall activation)
        {
            this.activation = activation;

            Scriptable parent = activation.getParentScope();
            setParentScope(parent);
            setPrototype(ScriptableObject.getObjectPrototype(parent));

            args = activation.originalArgs;
            lengthObj = args.Length;

            NativeFunction f = activation.function;
            calleeObj = f;

            int version = f.getLanguageVersion();
            if (version <= Context.VERSION_1_3
                && version != Context.VERSION_DEFAULT)
            {
                callerObj = null;
            }
            else
            {
                callerObj = NOT_FOUND;
            }
        }


        public override String getClassName()
        {
            return "Object";
        }


        public override bool has(int index, Scriptable start)
        {
            if (0 <= index && index < args.Length)
            {
                if (args[index] != NOT_FOUND)
                {
                    return true;
                }
            }
            return base.has(index, start);
        }


        public override Object get(int index, Scriptable start)
        {
            if (0 <= index && index < args.Length)
            {
                Object value = args[index];
                if (value != NOT_FOUND)
                {
                    if (sharedWithActivation(index))
                    {
                        NativeFunction f = activation.function;
                        String argName = f.getParamOrVarName(index);
                        value = activation.get(argName, activation);
                        if (value == NOT_FOUND) Kit.codeBug();
                    }
                    return value;
                }
            }
            return base.get(index, start);
        }

        private bool sharedWithActivation(int index)
        {
            NativeFunction f = activation.function;
            int definedCount = f.getParamCount();
            if (index < definedCount)
            {
                // Check if argument is not hidden by later argument with the same
                // name as hidden arguments are not shared with activation
                if (index < definedCount - 1)
                {
                    String argName = f.getParamOrVarName(index);
                    for (int i = index + 1; i < definedCount; i++)
                    {
                        if (argName == f.getParamOrVarName(i))
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            return false;
        }

        public override void put(int index, Scriptable start, Object value)
        {
            if (0 <= index && index < args.Length)
            {
                if (args[index] != NOT_FOUND)
                {
                    if (sharedWithActivation(index))
                    {
                        String argName;
                        argName = activation.function.getParamOrVarName(index);
                        activation.put(argName, activation, value);
                        return;
                    }
                    lock (this)
                    {
                        if (args[index] != NOT_FOUND)
                        {
                            if (args == activation.originalArgs)
                            {
                                args = (Object[])args.Clone();
                            }
                            args[index] = value;
                            return;
                        }
                    }
                }
            }
            base.put(index, start, value);
        }

        public void delete(int index)
        {
            if (0 <= index && index < args.Length)
            {
                lock (this)
                {
                    if (args[index] != NOT_FOUND)
                    {
                        if (args == activation.originalArgs)
                        {
                            args = (Object[])args.Clone();
                        }
                        args[index] = NOT_FOUND;
                        return;
                    }
                }
            }
            base.delete(index);
        }

        // #string_id_map#

        private const int
            Id_callee = 1,
            Id_length = 2,
            Id_caller = 3,

            MAX_INSTANCE_ID = 3;


        public override int getMaxInstanceId()
        {
            return MAX_INSTANCE_ID;
        }


        public override int findInstanceIdInfo(String s)
        {
            int id;
            // #generated# Last update: 2007-05-09 08:15:04 EDT
            id = 0; String X = null; int c;
            if (s.Length == 6)
            {
                c = s.ToCharArray()[5];
                if (c == 'e') { X = "callee"; id = Id_callee; }
                else if (c == 'h') { X = "length"; id = Id_length; }
                else if (c == 'r') { X = "caller"; id = Id_caller; }
            }
            if (X != null && X != s && !(X == s)) id = 0;
            goto L0;

        L0: ;
            // #/generated#

            if (id == 0) return base.findInstanceIdInfo(s);

            int attr;
            switch (id)
            {
                case Id_callee:
                case Id_caller:
                case Id_length:
                    attr = DONTENUM;
                    break;
                default: throw new Exception();
            }
            return instanceIdInfo(attr, id);
        }

        // #/string_id_map#


        public override String getInstanceIdName(int id)
        {
            switch (id)
            {
                case Id_callee: return "callee";
                case Id_length: return "length";
                case Id_caller: return "caller";
            }
            return null;
        }

        public override Object getInstanceIdValue(int id)
        {
            switch (id)
            {
                case Id_callee: return calleeObj;
                case Id_length: return lengthObj;
                case Id_caller:
                    {
                        Object value = callerObj;
                        if (value == UniqueTag.NULL_VALUE) { value = null; }
                        else if (value == null)
                        {
                            NativeCall caller = activation.parentActivationCall;
                            if (caller != null)
                            {
                                value = caller.get("arguments", caller);
                            }
                        }
                        return value;
                    }
            }
            return base.getInstanceIdValue(id);
        }


        public override void setInstanceIdValue(int id, Object value)
        {
            switch (id)
            {
                case Id_callee: calleeObj = value; return;
                case Id_length: lengthObj = value; return;
                case Id_caller:
                    callerObj = (value != null) ? value : UniqueTag.NULL_VALUE;
                    return;
            }
            base.setInstanceIdValue(id, value);
        }


        public override Object[] getIds(bool getAll)
        {
            Object[] ids = base.getIds(getAll);
            if (getAll && args.Length != 0)
            {
                bool[] present = null;
                int extraCount = args.Length;
                for (int i = 0; i != ids.Length; ++i)
                {
                    Object id = ids[i];
                    if (id is int)
                    {
                        int index = Convert.ToInt32(id);
                        if (0 <= index && index < args.Length)
                        {
                            if (present == null)
                            {
                                present = new bool[args.Length];
                            }
                            if (!present[index])
                            {
                                present[index] = true;
                                extraCount--;
                            }
                        }
                    }
                }
                if (extraCount != 0)
                {
                    Object[] tmp = new Object[extraCount + ids.Length];
                    Array.Copy(ids, 0, tmp, extraCount, ids.Length);
                    ids = tmp;
                    int offset = 0;
                    for (int i = 0; i != args.Length; ++i)
                    {
                        if (present == null || !present[i])
                        {
                            ids[offset] = i;
                            ++offset;
                        }
                    }
                    if (offset != extraCount) Kit.codeBug();
                }
            }
            return ids;
        }


    }
}
